package com.shqcjd.yunweiyanoperator.ui.activity.staff;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.pojo.ExpertBean;
import com.shqcjd.yunweiyanoperator.model.pojo.StaffManageBean;
import com.shqcjd.yunweiyanoperator.ui.adapter.BusinessExpertAdapter;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.Config;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.util.WrapContentLinearLayoutManager;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 个人专家
 */
public class PersonalExpertActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener{
    @BindView(R.id.btn_finish)
    ImageView btnFinish;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_business_expert)
    EditText etSearch;
    @BindView(R.id.rv_business_expert)
    RecyclerView rvBusinessExpert;
    @BindView(R.id.sr_business_expert)
    SwipeRefreshLayout swipeLayout;

    private Context mContext;
    private BusinessExpertAdapter businessExpertAdapter;
    private static final int PAGE_SIZE = Config.PAGE_TOTAL;
    private int mNextRequestPage = 1;
    private String keyword = "";
    private List<StaffManageBean.ListBean> mList = new ArrayList<>();
    private View notDataView;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_personal_expert;
    }

    @Override
    public void initView() {
        mContext = this;
        tvTitle.setText("查找个人专家");
        notDataView = getLayoutInflater().inflate(R.layout.layout_no_data, (ViewGroup) rvBusinessExpert.getParent(), false);
        initRefreshLayout();
        rvBusinessExpert.setLayoutManager(new WrapContentLinearLayoutManager(mContext));
        businessExpertAdapter = new BusinessExpertAdapter();
        rvBusinessExpert.setAdapter(businessExpertAdapter);
        businessExpertAdapter.setOnLoadMoreListener(this,rvBusinessExpert);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                keyword = editable.toString();
                refresh();
            }
        });
        businessExpertAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ExpertBean.ListBean item = (ExpertBean.ListBean) adapter.getItem(position);
                Intent intent = new Intent(mContext,ContactsDetailsActivity.class);
                intent.putExtra("isAddFriends", true);
                intent.putExtra("remoteId", item.id);
                intent.putExtra("userName", item.userName);
                intent.putExtra("phoneNumber", item.phoneNumber);
                intent.putExtra("businessName", item.businessName);
                intent.putExtra("maintainInfo", item.info);
                intent.putExtra("acceptAppCode", item.appCode);
                intent.putExtra("friendId", item.id);
                startActivity(intent);

            }
        });
    }

    @Override
    public void initData() {
        refresh();
    }

    private void initRefreshLayout() {
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        swipeLayout.setRefreshing(true);
    }

    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }

    private void refresh() {
        mNextRequestPage = 1;
        businessExpertAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        Map<String, String> map = new HashMap<>();
        map.put("keyword", keyword);
        map.put("page", mNextRequestPage+"");
        map.put("size", PAGE_SIZE+"");
        ApiService.getPersonalExpert(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<ExpertBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        swipeLayout.setRefreshing(true);
                    }

                    @Override
                    public void _onNext(ResponseData<ExpertBean> retData) {
                        if (retData.retCode == 10000) {
                            setData(true, retData.data.list,businessExpertAdapter);
                        } else {
                            ToastUtils.showShort(mContext,retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext,errorMessage);
                        businessExpertAdapter.setEnableLoadMore(true);
                        swipeLayout.setRefreshing(false);
                    }
                    @Override
                    public void onComplete() {
                        super.onComplete();
                        businessExpertAdapter.setEnableLoadMore(true);
                        swipeLayout.setRefreshing(false);
                    }
                });
    }

    private void loadMore() {
        Map<String, String> map = new HashMap<>();
        map.put("keyword", keyword);
        map.put("page", mNextRequestPage+"");
        map.put("size", PAGE_SIZE+"");
        ApiService.getPersonalExpert(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<ExpertBean>>() {
                    @Override
                    public void _onNext(ResponseData<ExpertBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            boolean isRefresh =mNextRequestPage ==1;
                            setData(isRefresh, retData.data.list,businessExpertAdapter);
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                        businessExpertAdapter.loadMoreFail();
                    }
                });
    }

    private void setData(boolean isRefresh, List data,BaseQuickAdapter adapter) {

        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            if (size > 0) {
                adapter.setNewData(data);
            } else {
                adapter.setNewData(null);
                adapter.setEmptyView(notDataView);
            }
        } else {
            if (size > 0) {
                adapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            adapter.loadMoreEnd(isRefresh);
        } else {
            adapter.loadMoreComplete();
        }
    }



    @OnClick(R.id.btn_finish)
    public void onViewClicked() {
        finish();
    }
}
